<!--
 * @Author: zsc
 * @Date: 2022-06-13 21:56:52
 * @LastEditors: zsc
 * @LastEditTime: 2022-07-26 21:38:38
 * @Description:
-->

<template>
  <div class="app-container">
    <!--    功能-->
    <!--    查询条件-->
    <el-card class="app-container-tools">
      <div class="app-container-tools-search">
        <entrance />
      </div>

    </el-card>
    <el-card class="app-container-tools">
      <div class="app-container-tools-search">
        <span>楼宇名称：</span>
        <el-input v-model="WHERE.search" class="k-width-150-p k-mr-10" />

        <el-button type="primary" @click="_search">查询</el-button>
        <el-button type="primary" @click="_reset">重置</el-button>
      </div>
      <div class="app-container-tools-action">
        <el-button v-permission="['BD:BUILDING:ADD']" type="primary" style=" margin-left: 10px" @click="handleCreate">
          新增
        </el-button>
        <el-button v-permission="['BD:BUILDING:ADD']" class="k-mr-10"> <el-upload
          action=""
          :show-file-list="false"
          :multiple="false"
          :file-list="fileList"
          :before-upload="uploadChangeHandel"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        >导入</el-upload>
        </el-button>
      </div>
    </el-card>

    <el-card>
      <!--    表格-->
      <el-table
        ref="tb"
        v-loading="LOADING"
        :data="TABLE_DATA"
        :size="SIZE"
        border
        :height="LIST_HEIGHT"
        style="width: 100%"
        @selection-change="_handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <template v-for="(item) in setting">
          <el-table-column
            v-if="item.key === 'action'"
            :key="item.id"
            :label="item.name"
            :prop="item.key"
            :width="item.value"
          >
            <template slot-scope="scope">

              <el-button @click="handleScan(scope.row)">基础信息</el-button>
              <!--              <el-button @click="handleVisitor(scope.row)">访客管理</el-button>-->
              <el-button v-permission="['BD:BUILDING:GATE']" @click="handleGate(scope.row)">闸机管理</el-button>
              <el-button @click="handleCompany(scope.row)">入驻单位</el-button>

              <el-button v-permission="['BD:BUILDING:TAX']">税收情况</el-button>
              <el-button v-permission="['BD:ROOM']" @click="handleRoom(scope.row)">房间管理</el-button>
              <el-button v-permission="['BD:BUILDING:EDIT']" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button v-permission="['BD:BUILDING:DEL']" @click="handleDel(scope.row)">删除</el-button>
            </template>

          </el-table-column>
          <el-table-column
            v-else-if="item.key === 'area'"
            :key="item.id"
            :label="item.name"
            :prop="item.key"
            :width="item.value"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.region_info.street_name }}</span>
            </template>

          </el-table-column>
          <el-table-column
            v-else-if="item.key === 'statusDisplay'"
            :key="item.id"
            :label="item.name"
            :prop="item.key"
            :width="item.value"
          >
            <template slot-scope="scope">
              <span>{{ handleGetstatus(scope.row.status) }}</span>
            </template>

          </el-table-column>
          <el-table-column
            v-else
            :key="item.id"
            :label="item.name"
            :prop="item.key"
            :width="item.value"
          />
        </template>
      </el-table>
      <!--    分页-->
      <pagination />
      <!--    弹窗-->
      <form-modal :visible.sync="FORM_VISIBLE" :type="FORM_TYPE" :data="FORM_DATA" @refresh="_search" />
      <gate-modal :visible.sync="gateVisible" :data="gateData" />
      <scan-modal :visible.sync="scanVisible" :data="scanData" />
      <company-modal :visible.sync="companyVisible" :building-id="buildingId" />
      <room-modal
        :visible.sync="roomVisible"
        :building-id="buildingId"
        :building-name="buildingName"
        :region-id="regionId"
      />
      <el-dialog :visible.sync="qrcode_visible" @opened="handelqr()">
        <div style="width: 210px;height: 210px;margin: auto;border: #000 1px solid;display: flex">
          <div ref="qrcode" style="margin: auto" />
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import list from '@/list'
import BuildingClass from '@/models/building-class'
import { buildingGetList, buildingDel, buildingBulkCreate } from '@/api/building'
import formModal from './components/form'
import gateModal from './components/gate'
import scanModal from './components/scan'
import companyModal from './components/companyList'
import roomModal from './components/room/roomList'
import QRCode from 'qrcodejs2'
import entrance from '@/views/entrance'
import * as XLSX from 'xlsx'
const buildingClass = new BuildingClass()
export default {
  name: 'DeepInterpretationOrder',
  components: { formModal, gateModal, scanModal, companyModal, roomModal, entrance },
  mixins: [list],
  data() {
    return {
      gateVisible: false,
      gateData: '',
      scanVisible: false,
      scanData: 0,
      companyVisible: false,
      roomVisible: false,
      buildingId: 0,
      qrcode_visible: false,
      regionId: 0,
      caseRequestURLType: '',
      setting: buildingClass.list(),
      WHERE: {
        buildingName: '' // 访问类型
      },
      buildingName: '',
      statusmMap: [
        { val: 1, text: '已建' },
        { val: 2, text: '在建' },
        { val: 3, text: '待建' }
      ],
      fileList: []

    }
  },
  created() {
    this.LIST_API = buildingGetList
  },
  mounted() {
  },
  methods: {
    handleCreate() {
      console.log('添加')
      this.FORM_TYPE = 'create'
      this.FORM_VISIBLE = true
      this.FORM_DATA = {}
    },
    handleEdit(item) {
      console.log('更新')
      this.FORM_TYPE = 'edit'
      this.FORM_VISIBLE = true
      this.FORM_DATA = item
    },
    // handleVisitor() {
    //   this.$router.push('/building/visitor')
    // },
    handleScan(item) {
      console.log('楼宇资料')
      this.scanVisible = true
      this.scanData = item.id
    },
    handleCompany(item) {
      console.log('企业列表')
      this.companyVisible = true
      this.buildingId = item.id
    },
    handleImport() {
      console.log('导入')
      this.$notify.success('导入')
    },
    handleDel(item) {
      this.$confirm('确认删除？')
        .then(_ => {
          buildingDel(item.id).then(p => {
            this._showSuccess('删除成功')
            this._search()
          })
        })
        .catch(_ => {
        })
      console.log('删除', item)
    },
    handleGate(item) {
      console.log('闸机管理', item)
      this.gateVisible = true
      this.gateData = item.id
    },
    handleGetstatus(item) {
      return this.statusmMap.find(p => p.val === item).text
    },
    handleqrCode(item) {
      console.log('楼宇码')
      this.buildingId = item.id
      this.regionId = item.region_id
      this.qrcode_visible = true
    },
    handelqr() {
      if (this.qrcode) {
        this.qrcode.makeCode(`https://data.citylaboratory.cn/company?building_id=${this.buildingId}&region_id=${this.regionId}`)
      } else {
        this.qrcode = new QRCode(this.$refs.qrcode, {
          text: `https://data.citylaboratory.cn/company?building_id=${this.buildingId}&region_id=${this.regionId}`,
          width: 210,
          height: 210,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        })
      }
    },
    handleRoom(item) {
      console.log('房间管理')
      this.buildingId = item.id
      this.buildingName = item.name
      this.regionId = item.region_id
      this.roomVisible = true
    },
    csvToArray(str, delimiter = ',') {
      const header_cols = str.slice(0, str.indexOf('\n')).split(delimiter)
      const row_data = str.slice(str.indexOf('\n') + 1).split('\n')
      const arr = row_data.map(function(row) {
        const values = row.split(delimiter)
        const el = header_cols.reduce(function(object, header, index) {
          object[header] = values[index]
          return object
        }, {})
        return el
      })
      return arr
    },
    /**
     * 临时使用
     * TODO
     */
    async uploadChangeHandel(file) {
      const reader = new FileReader(file)
      reader.readAsBinaryString(file)
      reader.onload = async(e) => {
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheet = workbook.Sheets
        var aoa = XLSX.utils.sheet_to_csv(sheet[workbook.SheetNames[0]])
        const arrData = this.csvToArray(aoa, ',').filter(
          (p) => { return p['楼宇名称'] }
        )
        const upData = arrData.map((p) => {
          return {
            'region_id': 34,
            'name': p['楼宇名称'],
            'address': p['注册地址'],
            'total_area': p['建筑面积（m²）'],
            'business_area': p['商务面积（m²）'],
            'status': 1,
            'total_height': 0,
            'ground_height': 0,
            'underground_height': 0,
            'grounp_floor': 0,
            'undergrounp_floor': 0,
            'property_name': '',
            'property_contact': '',
            begin_time: '2022-07-17 20:17:11',
            carport_cost: '',
            carport_number: 0,
            note: '',
            over_time: '2022-07-17 20:17:11',
            property_cost: '',
            property_level: '',
            property_phone: ''

          }
        })
        console.log(upData)
        buildingBulkCreate({ upData }).then(
          p => {
            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: `
            操作成功!
          `,
              type: 'success'
            })
            this._getList()
          }
        )

        // await focusCreate({ list: upData })
      }
      this.fileList = []
      return false
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/list/index.scss';
</style>
